from plugin import GrapCheck, LogCheck, NginxAccessCheck, ProcessCheck
from env import Env
import threading
import time

# 全局标志，用于控制是否继续创建新的定时任务
running = True


def run_check(check_func, flush_interval):
    """
    运行指定的检查函数，并按照指定的刷新间隔循环执行
    :param check_func: 要执行的检查函数
    :param flush_interval: 刷新间隔（秒）
    """
    if flush_interval == -1:
        check_func()
        return
    global running
    while running:
        check_func()
        time.sleep(flush_interval)


if __name__ == '__main__':
    # 获取不同类型的刷新间隔
    graph_flush_interval = Env.get_flush_interval("storage")
    ssh_flush_interval = Env.get_flush_interval("ssh")
    nginx_flush_interval = Env.get_flush_interval("nginx")
    process_flush_interval = Env.get_flush_interval("process")

    # 为每个检查任务启动一个线程
    graph_thread = threading.Thread(target=run_check, args=(GrapCheck.scan, graph_flush_interval))
    log_thread = threading.Thread(target=run_check, args=(LogCheck.scan, ssh_flush_interval))
    nginx_thread = threading.Thread(target=run_check, args=(NginxAccessCheck.scan, nginx_flush_interval))
    process_thread = threading.Thread(target=run_check, args=(ProcessCheck.scan, process_flush_interval))

    # 启动线程
    graph_thread.start()
    log_thread.start()
    nginx_thread.start()
    process_thread.start()
    try:
        # 主线程等待，直到用户按下 Ctrl+C
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        # 当用户按下 Ctrl+C 时，设置 running 为 False，停止所有线程
        running = False
        # 等待所有线程结束
        graph_thread.join()
        log_thread.join()
        nginx_thread.join()
        process_thread.join()
    pass
